import 'dart:async';

import 'package:earclean/app/routes/app_pages.dart';
import 'package:earclean/app/util/common_utils.dart';
import 'package:earclean/app/util/string_util.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:shanyan/shanYanResult.dart';
import 'package:shanyan/shanYanUIConfig.dart';
import 'package:shanyan/shanyan.dart';

import '../../../request/request_main.dart';

class LoginController extends GetxController {
  //TODO: Implement LoginController
  final protect = false.obs;
  String phone = '';
  String code = '';
  RxString codeStr = '获取验证码'.obs;
  //计时器
  late Timer _timer;
  //获取验证码总时间
  int _count = 60;
  final enbleClick = true.obs;
  final showview = false.obs;

  final oneKeyLoginManager = OneKeyLoginManager();

  bool isone = false;

  //获取验证码
  getCode() async {
    if (enbleClick.value == true) {
      if (isNotEmpty(phone) == false) {
        EasyLoading.showToast('请输入正确的手机号');
        return;
      }

      Map? m = await RequestMain.postUrl({'mobile': phone});
      if (m.isNotEmpty && m['code'].toString() == "200") {
        EasyLoading.showToast('发送成功');
        startTimer();
      }
    }
  }

  changeAgree() {
    protect.value = !protect.value;
  }

  void startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      _count--;
      enbleClick.value = false;
      if (_count == 0) {
        enbleClick.value = true;
        _timer.cancel();
        _count = 60;
        codeStr.value = "重新发送";
      } else {
        codeStr.value = '$_count' + "秒";
      }
    });
  }

  send() async {
    if (protect.value == false) {
      EasyLoading.showToast('请同意用户隐私协议');
      return;
    }
    Map? m = await RequestMain.getUrl({'mobile': phone, 'code': code});
    if (m.isNotEmpty && m['code'].toString() == "200") {
      showview.value = false;
      EasyLoading.showToast('登录成功');
      if (m['data'] is Map) {
        Map data = m['data'];
        box.write("key", data['key']);
        box.write("mobile", phone);
        box.write("kefu", data['kefu'].trim());
        box.write("tab", data['tab']);

        Map setData = await RequestMain.getUrl({},
            turl: 'https://fjbamz.jiliol.net/sign/?a=my');
        if (setData.isNotEmpty && setData['code'].toString() == "200") {
          if (setData['data'] is Map) {
            Map data = setData['data'];
            // 已满文案(为空可预约)
            box.write("full", data['full'] ?? "");
            // 原生弹窗(重要)
            box.write("box", data['box'] ?? []);
            // 应用市场好评弹窗 0:不弹,1:弹
            box.write("rank", data['rank'].toString());
            // 默认选择的tabbar
            box.write("tab", int.parse((data['tab'] ?? "0").toString()));
            // 默认进去登录页 0  不先进登录 1  先进登录
            box.write("prelogin", data['prelogin'].toString());
            // 客服电话或邮箱
            box.write("kefu", data['kefu'] ?? '');
            // 判断接口中的quan，如果=1，直接跳转到接口中的find_url的h5页面，全屏展示，=0，还是当前的状态即可
            box.write("quan", data['quan'].toString());
            box.write("find_url", data['find_url'].toString());
            // 我的订单
              box.write("my_need_url", data['my_need_url'].toString());
              // 我的钱包
              box.write("my_account", data['my_account'].toString());
              // 消息
              box.write("chat_url", data['chat_url'].toString());
              // 客服
              box.write("kefu", data['kefu'].trim());
               // 支付方式
              box.write("pconfs", data['pconfs']??[]);
          }
        }
        Get.offAllNamed(Routes.TABLE);
      } else {
        Map setData = await RequestMain.getUrl({},
            turl: 'https://fjbamz.jiliol.net/sign/?a=my');
        if (setData.isNotEmpty && setData['code'].toString() == "200") {
          if (setData['data'] is Map) {
            Map data = setData['data'];
            // 已满文案(为空可预约)
            box.write("full", data['full'] ?? "");
            // 应用市场好评弹窗 0:不弹,1:弹
            box.write("rank", data['rank'].toString());
            // 默认选择的tabbar
            box.write("tab", int.parse((data['tab'] ?? "0").toString()));
            // 默认进去登录页 0  不先进登录 1  先进登录
            box.write("prelogin", data['prelogin'].toString());
            // 客服电话或邮箱
            box.write("kefu", data['kefu'] ?? '');
            // 判断接口中的quan，如果=1，直接跳转到接口中的find_url的h5页面，全屏展示，=0，还是当前的状态即可
            box.write("quan", data['quan'].toString());
            box.write("find_url", data['find_url'].toString());
            // 我的订单
              box.write("my_need_url", data['my_need_url'].toString());
              // 我的钱包
              box.write("my_account", data['my_account'].toString());
              // 消息
              box.write("chat_url", data['chat_url'].toString());
              // 客服
              box.write("kefu", data['kefu'].trim());
               // 支付方式
              box.write("pconfs", data['pconfs']??[]);
          }
        }
        Get.offAllNamed(Routes.TABLE);
      }
    }
  }

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    oneLogin();
    super.onReady();
  }

  oneLogin() {
    dynamic oneKeyInit = box.read("oneKeyInit");
    if (oneKeyInit != null && oneKeyInit == true) {
      oneKeyLoginManager.getPhoneInfo().then((ShanYanResult value1) {
        if (value1.code == 1000) {
          ShanYanUIConfig shanYanUIConfig = ShanYanUIConfig();
          shanYanUIConfig.ios.isFinish = true;
          // 背景图片
          shanYanUIConfig.ios.setAuthBGImgPath = 'bg';
          // logo
          shanYanUIConfig.ios.setLogoImgPath = "logo";
          shanYanUIConfig.ios.setLogoHidden = false;
          // 手机号
          shanYanUIConfig.ios.setNumberColor = "#000000";
          shanYanUIConfig.ios.setNumberSize = 20;
          shanYanUIConfig.ios.setNumberBold = true;
          shanYanUIConfig.ios.setNumberTextAlignment = iOSTextAlignment.right;
          // 一键登录
          shanYanUIConfig.ios.setLogBtnText = "一键登录";
          shanYanUIConfig.ios.setLogBtnTextColor = "#ffffff";
          shanYanUIConfig.ios.setLoginBtnTextSize = 16;
          shanYanUIConfig.ios.setLoginBtnTextBold = false;
          shanYanUIConfig.ios.setLoginBtnBgColor = "#51813A";
          shanYanUIConfig.ios.setLoginBtnCornerRadius = 5;
          shanYanUIConfig.ios.setPrivacyTextSize = 10;
          shanYanUIConfig.ios.setPrivacyTextBold = false;
          // 隐私条款

          //logo
          shanYanUIConfig.ios.layOutPortrait.setLogoTop =
              1.sw * 522 / 750 - 190;
          shanYanUIConfig.ios.layOutPortrait.setLogoWidth = 70;
          shanYanUIConfig.ios.layOutPortrait.setLogoHeight = 70;
          shanYanUIConfig.ios.layOutPortrait.setLogoCenterX = 0;

          //手机号控件
          shanYanUIConfig.ios.layOutPortrait.setNumFieldTop =
              1.sw * 522 / 750 - 50;
          shanYanUIConfig.ios.layOutPortrait.setNumFieldCenterX = 0;
          shanYanUIConfig.ios.layOutPortrait.setNumFieldHeight = 40;
          shanYanUIConfig.ios.layOutPortrait.setLogBtnWidth = 1.sw;

          // //一键登录按钮
          shanYanUIConfig.ios.layOutPortrait.setLogBtnTop =
              1.sw * 522 / 750 + 15;
          shanYanUIConfig.ios.layOutPortrait.setLogBtnCenterX = 0;
          shanYanUIConfig.ios.layOutPortrait.setLogBtnHeight = 45;
          shanYanUIConfig.ios.layOutPortrait.setLogBtnWidth = .9.sw;

          shanYanUIConfig.ios.setPrivacyTextSize = 12;
          shanYanUIConfig.ios.setPrivacyTextBold = false;
          shanYanUIConfig.ios.setAppPrivacyTextAlignment =
              iOSTextAlignment.left;
          shanYanUIConfig.ios.setPrivacySmhHidden = true;
          shanYanUIConfig.ios.setAppPrivacyLineSpacing = 5;
          shanYanUIConfig.ios.setAppPrivacyNeedSizeToFit = false;
          shanYanUIConfig.ios.setAppPrivacyAbbreviatedName = "和";

          shanYanUIConfig.ios.setAppPrivacyColor = ["#808080", "#51813A"];

          shanYanUIConfig.ios.setAppPrivacyNormalDesTextFirst = "同意";
          shanYanUIConfig.ios.setAppPrivacyNormalDesTextSecond = "和";
          shanYanUIConfig.ios.setPrivacyNavTextSize = 12;

          oneKeyLoginManager.setLoadingVisibility(false);

          // shanYanUIConfig.ios.setAppPrivacyFirst = [
          //   "《用户协议》",
          //   "https://iamz.jiliol.net/LegalDocuments/UserAgreement.html"
          // ];
          // shanYanUIConfig.ios.setAppPrivacySecond = [
          //   "《隐私政策》",
          //   "https://iamz.jiliol.net/LegalDocuments/PrivacyPolicy.html"
          // ];

          shanYanUIConfig.ios.setPrivacyState = true;
          shanYanUIConfig.ios.setCheckBoxVerticalAlignmentToAppPrivacyCenterY =
              true;
          shanYanUIConfig.ios.setUncheckedImgPath = "icon_wxz";
          shanYanUIConfig.ios.setCheckedImgPath = "icon";
          shanYanUIConfig.ios.setCheckBoxWH = [25, 25];
          shanYanUIConfig.ios.setCheckBoxImageEdgeInsets = [5, 5, 5, 5];
          shanYanUIConfig.ios.setSloganTextHidden = true;
          shanYanUIConfig.ios.setSloganTextSize = 14;

          //授权页 创蓝slogan（创蓝253提供认证服务）
          shanYanUIConfig.ios.layOutPortrait.setShanYanSloganHeight = 15;
          shanYanUIConfig.ios.layOutPortrait.setShanYanSloganLeft = 0;
          shanYanUIConfig.ios.layOutPortrait.setShanYanSloganRight = 0;
          shanYanUIConfig.ios.layOutPortrait.setShanYanSloganBottom = 20;

          //授权页 slogan（***提供认证服务）
          shanYanUIConfig.ios.layOutPortrait.setSloganHeight = 15;
          shanYanUIConfig.ios.layOutPortrait.setSloganLeft = 0;
          shanYanUIConfig.ios.layOutPortrait.setSloganRight = 0;
          shanYanUIConfig.ios.layOutPortrait.setSloganBottom = 20;

          //隐私协议
//    shanYanUIConfig.ios.layOutPortrait.setPrivacyHeight = 50;
          shanYanUIConfig.ios.layOutPortrait.setPrivacyLeft = 50;
          shanYanUIConfig.ios.layOutPortrait.setPrivacyRight = 10;
          shanYanUIConfig.ios.layOutPortrait.setPrivacyTop =
              1.sw * 522 / 750 + 15 + 45 + 75;
          shanYanUIConfig.ios.layOutPortrait.setPrivacyCenterX = 0;

          List<ShanYanCustomWidgetIOS> shanyanCustomWidgetIOS = [];
          final String btnWidgetId = "other_custom_button"; // 标识控件 id
          ShanYanCustomWidgetIOS buttonWidgetiOS = ShanYanCustomWidgetIOS(
              btnWidgetId, ShanYanCustomWidgetType.Button);
          buttonWidgetiOS.textContent = "其他登录方式";
          buttonWidgetiOS.top = 1.sw * 522 / 750 + 15 + 45;
          buttonWidgetiOS.left = 20;
          // buttonWidgetiOS.width = .8.sw;
          buttonWidgetiOS.height = 45;
          // buttonWidgetiOS.backgroundColor = "#ff0000";
          buttonWidgetiOS.textColor = "#51813A";

          buttonWidgetiOS.textAlignment = iOSTextAlignment.left;
          buttonWidgetiOS.borderWidth = 0;
          buttonWidgetiOS.textFont = 14;
          buttonWidgetiOS.isFinish = false;
          // buttonWidgetiOS.borderColor = "#A44CE3";
          shanyanCustomWidgetIOS.add(buttonWidgetiOS);

          final String navRightBtnWidgetId =
              "other_custom_nav_left_button"; // 标识控件 id
          ShanYanCustomWidgetIOS navRightButtonWidgetiOS =
              ShanYanCustomWidgetIOS(
                  navRightBtnWidgetId, ShanYanCustomWidgetType.Button);
          navRightButtonWidgetiOS.navPosition =
              ShanYanCustomWidgetiOSNavPosition.navleft;
          navRightButtonWidgetiOS.isFinish = false;
          if (box.read("prelogin").toString() != '1') {
            navRightButtonWidgetiOS.image = '';
            navRightButtonWidgetiOS.width = 0;
            navRightButtonWidgetiOS.height = 0;
          } else {
            navRightButtonWidgetiOS.image = '';
            navRightButtonWidgetiOS.width = 0;
            navRightButtonWidgetiOS.height = 0;
          }
          navRightButtonWidgetiOS.textAlignment = iOSTextAlignment.center;
          shanyanCustomWidgetIOS.add(navRightButtonWidgetiOS);

          shanYanUIConfig.ios.widgets = shanyanCustomWidgetIOS;
          oneKeyLoginManager.setAuthThemeConfig(uiConfig: shanYanUIConfig);

          oneKeyLoginManager
              .openLoginAuth()
              .then((ShanYanResult shanYanResult) {
            if (1000 == shanYanResult.code) {
              //拉起授权页成功
              oneKeyLoginManager.setOneKeyLoginListener((shanYanResult) {
                if (shanYanResult.code == 1000) {
                  oneKeyLogin(shanYanResult.token!);
                }
              });
              oneKeyLoginManager.addClikWidgetEventListener((shanYanResult) {
                if (shanYanResult == 'other_custom_button') {
                  showview.value = true;
                  isone = true;
                  oneKeyLoginManager.finishAuthControllerCompletion();
                } else if (shanYanResult == 'other_custom_nav_left_button') {
                  showview.value = true;
                  isone = true;
                  oneKeyLoginManager.finishAuthControllerCompletion();
                }
              });
            } else {
              //拉起授权页失败
              showview.value = true;
              // EasyLoading.showToast(shanYanResult.message ?? "");
            }
          });
        } else {
          //拉起授权页失败
          showview.value = true;
          // EasyLoading.showToast(value1.message ?? "");
        }
        // phone.value = value1.
      });
    } else {
      showview.value = true;
    }
  }

  oneKeyLogin(String keytoken) async {
    Map? m = await RequestMain.postUrl({
      'result': {'token': keytoken}
    }, turl: 'https://fjbamz.jiliol.net/sign/?a=index');
    if (m.isNotEmpty && m['code'].toString() == "200") {
      EasyLoading.showToast('登录成功');
      if (m['data'] is Map) {
        Map data = m['data'];
        box.write("key", data['key']);
        box.write('oneKey', '1');
        box.write("mobile", phone);
        box.write("kefu", data['kefu'].trim());
        box.write("showtab", data['tab']);
      }
      // 获取设置
      Map setData = await RequestMain.getUrl({},
          turl: 'https://fjbamz.jiliol.net/sign/?a=my');
      if (setData.isNotEmpty && setData['code'].toString() == "200") {
        if (setData['data'] is Map) {
          Map data = setData['data'];
          // 已满文案(为空可预约)
          box.write("full", data['full'] ?? "");
          // 应用市场好评弹窗 0:不弹,1:弹
          box.write("rank", data['rank'].toString());
          // 默认选择的tabbar
          box.write("tab", int.parse(data['tab'] ?? "0"));
          // 客服
          box.write("kefu", data['kefu'] ?? "");
          // 是否直接打开登录页
          box.write("prelogin", data['prelogin'].toString());
          // 判断接口中的quan，如果=1，直接跳转到接口中的find_url的h5页面，全屏展示，=0，还是当前的状态即可
          box.write("quan", data['quan'].toString());
          box.write("find_url", data['find_url'].toString());
          // 我的订单
              box.write("my_need_url", data['my_need_url'].toString());
              // 我的钱包
              box.write("my_account", data['my_account'].toString());
              // 消息
              box.write("chat_url", data['chat_url'].toString());
              // 客服
              box.write("kefu", data['kefu'].trim());
               // 支付方式
              box.write("pconfs", data['pconfs']??[]);
        }
      }
      Get.offAllNamed(Routes.TABLE);
      Future.delayed(const Duration(milliseconds: 1000),
          () => {oneKeyLoginManager.finishAuthControllerCompletion()});
    } else {
      if (m['code'].toString() == "400") {
        oneKeyLoginManager.setLoadingVisibility(false);
        EasyLoading.showToast(m['msg'] ?? "登录失败");
      }
    }
  }

  @override
  void onClose() {}
}
